<template>
  <!-- scope.row是当前这一排的数据 -->
  <!-- 解决tag input输入框联动效果，为每行数据添加自己的 控制文本框显示隐藏效果的属性和文本框中输入的值 的属性，每当改变时就改变自己的值，这样其他的输入框就不会联动了 -->
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <el-row>
        <el-col>
          <el-alert
            title="注意：只允许为第三级分类设置相关参数"
            type="warning"
            show-icon
          >
          </el-alert>
        </el-col>
      </el-row>
      <el-row class="cate_opt">
        <span>选择商品分类： </span>
        <el-cascader
          v-model="selectCateKeys"
          :options="cateList"
          :props="cateProps"
          @change="handleChange"
        ></el-cascader>
      </el-row>
      <!-- tab页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addDialogVisble = true"
            >添加属性</el-button
          >
          <el-table :data="manyTableData" border stripe>
            <el-table-column type="expand">
              <template #default="scope">
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="handleClose(index, scope.row)"
                >
                  {{ item }}
                </el-tag>
                <el-input
                  v-if="scope.row.inputVisible"
                  ref="saveTagInput"
                  v-model="scope.row.inputValue"
                  class="input-new-tag"
                  size="mini"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" width="50" />
            <el-table-column prop="attr_name" label="参数名称" />
            <el-table-column prop="path" label="操作">
              <template #default="scope">
                <!-- 编辑按钮 -->
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editParam(scope.row.attr_id)"
                  >编辑</el-button
                >
                <!-- 删除按钮 -->
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteParam(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addDialogVisble = true"
            >添加属性</el-button
          >
          <el-table :data="onlyTableData" border stripe>
            <el-table-column type="expand">
              <template #default="scope">
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="handleClose(index, scope.row)"
                >
                  {{ item }}
                </el-tag>
                <el-input
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  class="input-new-tag"
                  size="mini"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" width="50" />
            <el-table-column prop="attr_name" label="属性名称" />
            <el-table-column prop="path" label="操作">
              <template #default="scope">
                <!-- 编辑按钮 -->
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editParam(scope.row.attr_id)"
                  >编辑</el-button
                >
                <!-- 删除按钮 -->
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteParam(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加属性 -->
    <el-dialog
      :visible.sync="addDialogVisble"
      :title="'添加' + titleText"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 内容主体区 -->
      <el-form
        ref="addFormRef"
        label-width="90px"
        :model="addForm"
        :rules="addFormRulse"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisble = false">取消</el-button>
          <el-button type="primary" @click="addParams">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 编辑 -->
    <el-dialog
      :visible.sync="editDialogVisble"
      :title="'修改' + titleText"
      width="50%"
      @close="editDialogClosed"
    >
      <!-- 内容主体区 -->
      <el-form
        ref="editFormRef"
        label-width="90px"
        :model="editForm"
        :rules="editFormRulse"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisble = false">取消</el-button>
          <el-button type="primary" @click="editParams">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { MessageBox,Message } from "element-ui";
export default {
  name: "Params",
  created() {
    this.getCateList();
  },
  beforeUpdate() {
    // console.log("beforeUpdate");
  },
  data() {
    return {
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 1,
      },
      // 商品分类列表
      cateList: [],
      // 级联选择框的配置对象
      cateProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      // 级联选择框双向绑定到的数组
      selectCateKeys: [],
      activeName: "many",
      manyTableData: [],
      onlyTableData: [],
      addDialogVisble: false,
      addForm: {
        attr_name: "",
      },
      // 表单验证规则对象
      addFormRulse: {
        attr_name: [
          {
            required: true,
            message: "请输入参数",
            trigger: "blur",
          },
        ],
      },
      editDialogVisble: false,
      editForm: {
        attr_name: "",
      },
      editFormRulse: {
        attr_name: [
          {
            required: true,
            message: "请输入参数",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    // 级联选择框选中项变化，会触发这个函数
    handleChange() {
      if (this.selectCateKeys.length !== 3) {
        this.selectCateKeys = [];
        this.manyTableData = [];
        this.onlyTableData = [];
        return;
      } else {
        // console.log(this.selectCateKeys);
        // 发起请求获取动态参数和静态属性
        this.getParamsDate();
      }
    },
    async getCateList() {
      const { data: res } = await this.$http.get("/categories");
      // console.log(res);
      if (res.meta.status !== 200)
        return this.$message.error("获取商品分类失败");
      this.cateList = res.data;
      // this.total = res.data.total;
    },
    // 点击tab
    handleClick(tab, event) {
      // console.log(tab, event);
      this.getParamsDate();
    },
    // 发起请求获取动态参数和静态属性
    async getParamsDate() {
      const { data: res } = await this.$http.get(
        `/categories/${this.cateId}/attributes`,
        {
          params: {
            sel: this.activeName,
          },
        }
      );
      // console.log(res);
      res.data.forEach((item) => {
        // 先判断attr_vals是否为空，如果为空就返回空白数组
        // console.log(item.attr_vals);
        item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
        // console.log(item.attr_vals);
        item.inputVisible = false;
        item.inputValue = "";
      });
      if (res.meta.status !== 200) {
        return this.$message.error("获取参数失败");
      }
      if (this.activeName === "many") {
        this.manyTableData = res.data;
        // console.log(this.manyTableData);
      } else {
        this.onlyTableData = res.data;
        // console.log(this.onlyTableData);
      }
    },
    // 监听添加对话框的关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    // 点击添加参数
    addParams() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName,
          }
        );
        // console.log(res);
        if (res.meta.status !== 201) return this.$message.error("添加参数失败");
        this.getParamsDate();
        this.$message.success("添加参数成功");
        this.addDialogVisble = false;
      });
    },
    // 点击编辑
    async editParam(attr_id) {
      console.log(attr_id);
      this.editDialogVisble = true;
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${attr_id}`,
        {
          params: {
            attr_sel: this.activeName,
          },
        }
      );
      if (res.meta.status !== 200) return this.$message.error("获取参数失败");
      // console.log(res);
      this.editForm = res.data;
    },
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    // 点击编辑确定按钮
    editParams() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName,
          }
        );
        // console.log(res);
        if (res.meta.status !== 200) return this.$message.error("更新失败");
        this.$message.success("更新成功");
        this.getParamsDate();
        this.editDialogVisble = false;
      });
    },
    // 点击删除按钮
    async deleteParam(attr_id) {
      // 因为confirm的返回值是promise所以可以用await async来修饰
      const Messageres = await MessageBox.confirm(
        "此操作将永久删除该参数,是否继续?",
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch(() => {
        Message({
          type: "info",
          message: "已取消删除",
        });
      });
      // 如果用户确认了删除,返回字符串confirm
      if (Messageres === "confirm") {
        const { data: res } = await this.$http.delete(
          `categories/${this.cateId}/attributes/${attr_id}`
        );
        if (res.meta.status !== 200) return this.$message.error("删除参数失败");
        this.$message.success("删除参数成功");
        this.getParamsDate();
      }
    },
    // 点击添加tag
    showInput(row) {
      row.inputVisible = true;
      // 为什么点击获取不到ref的标签
      // console.log(row);
      // 让文本自动获取焦点
      // $nextTick方法的作用，就是当页面上的元素被重新渲染之后，会执行$nextTick这个方法
      // console.log(this.$refs.addFormRef);
      // console.log(this.$refs.saveTagInput);
      this.$nextTick(() => {
        // console.log(this.$refs.saveTagInput);
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 键盘弹起，光标离开触发
    handleInputConfirm(row) {
      // console.log(row);
      row.attr_vals.push(row.inputValue.trim());
      row.inputVisible = false;
      row.inputValue = "";
      this.saveAttrVals(row);
    },
    // 修改参数的函数
    async saveAttrVals(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(","),
        }
      );
      if (res.meta.status !== 200) return this.$message.error("更新参数失败");
      this.$message.success("更新参数成功");
    },
    // 删除参数
    handleClose(index, row) {
      row.attr_vals.splice(index, 1);
      this.saveAttrVals(row);
    },
  },
  computed: {
    // 计算属性
    isBtnDisabled() {
      if (this.selectCateKeys.length !== 3) {
        return true;
      } else {
        return false;
      }
    },
    cateId() {
      if (this.selectCateKeys.length !== 3) {
        return null;
      } else {
        return this.selectCateKeys[2];
      }
    },
    titleText() {
      if (this.activeName === "many") {
        return "动态参数";
      } else {
        return "静态属性";
      }
    },
  },
};
</script>

<style lang="less" scoped>
.cate_opt {
  margin: 15px;
  span {
    line-height: 30px;
  }
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 120px;
}
</style>

